package com.youlu.campus.service.base.impl;

import com.youlu.campus.service.base.LockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class LockServiceImpl implements LockService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean tryLock(String key, long timeout, TimeUnit unit) {
        try {
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", timeout, unit);
            if (Objects.nonNull(flag) && flag) {
                return true;
            }
        } catch (Exception e) {
            log.error("LockService ,key:{},add lock error", key, e);
        }
        return false;
    }

    @Override
    public boolean tryLock(String key, long waitTime, long leaseTime, TimeUnit unit) {
        return false;
    }

    @Override
    public void lock(String key) {

    }

    @Override
    public void unLock(String key) {
        redisTemplate.delete(key);
    }

//    @Autowired
//    private RedissonClient redissonClient;
//
//
//    @Override
//    public boolean tryLock(String key, long timeout, TimeUnit unit) {
//        return tryLock(key, timeout,DEFAULT_EXPIRE_TIME, unit);
//    }
//
//    @Override
//    public boolean tryLock(String key, long waitTime, long leaseTime, TimeUnit unit) {
//        try {
//            RLock lock = redissonClient.getLock(key);
//            boolean res = lock.tryLock(waitTime, leaseTime, unit);
//            return res;
//        } catch (Exception e) {
//            log.error("获取redis锁异常, key is {}, timeout is {},leaseTime is {}, unit is {}.", key,
//                    waitTime, leaseTime, unit, e);
//            throw new BusinessException("获取redis锁异常");
//        }
//    }
//
//    @Override
//    public void lock(String key) {
//        RLock lock = redissonClient.getLock(key);
//        lock.lock();
//    }
//
//    @Override
//    public void unLock(String key) {
//        try {
//            RLock lock = redissonClient.getLock(key);
//            lock.unlock();
//        } catch (Exception e) {
//           log.error("redis解锁异常,key={}", key, e);
//        }
//
//    }
}
